/*
 This software is copyrighted by Reality Jockey, Ltd..  The following
 terms (the "Standard Improved BSD License") apply to all files associated with
 the software unless explicitly disclaimed in individual files:
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are
 met:
 
 1. Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above  
 copyright notice, this list of conditions and the following 
 disclaimer in the documentation and/or other materials provided
 with the distribution.
 3. The name of the author may not be used to endorse or promote
 products derived from this software without specific prior 
 written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY
 EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,   
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 *
 * pd_utils.m: utilities functions to start pd, and send messages to the pd
 * thread.
 */

#include "pd_utils.h"
#include "s_stuff.h"
#include "stdarg.h" // for va_list
#include "stdio.h"
#include <pthread.h>
#include <android/log.h>

pthread_t pdthread;

int sys_started;

// these functions are defined in libpd, but not declared in m_pd.h
extern int sys_main(int argc, char **argv);
extern void glob_evalfile(void *ignore, void *name, void *dir);

void rj_printhook(const char *s) {
#ifdef ANDROID
	__android_log_write(ANDROID_LOG_VERBOSE, "Pd", s);
#else
	fprintf(stderr, "%s", s);
	fflush(stderr);
#endif
}

// this function is passed to pthread_create to start the pd thread
void* startpd(void* arg) {
#ifdef HAVE_PD
	rj_printhook("START startpd(arg) WITH pthread");

	char* marg[] = {
		"THIS_IS_IGNORED",
		"-noprefs",
		"-nostdpath",
		"-nogui",
		"-nomidi",
		"-noadc", // NOTE (naim) No audio input at the moment.
		"-android", // Specify the Android Audio API.
		//"-open", "/sdcard/test.pd",
		//"-open", "/sdcard/metro_del_extra_osc_test.pd",
		//"-audiobuf", "500",
		"-rt",
		"-r", "22050",
		// for some reason, these are ignored
		// so we enforce that in s_audio_aqueue
		"-inchannels", "2",
		"-outchannels", "2"
    };
	sys_printhook = (t_printhook)rj_printhook;
	sys_main(sizeof(marg)/sizeof(char*), marg);
#endif /* HAVE_PD */
	return NULL;
}

void pd_start(void) {
#ifdef HAVE_PD
	rj_printhook("START pd_start()");
	sys_started = 0;
	pthread_create(&pdthread, NULL, startpd, NULL);
#endif /* HAVE_PD */
}

// this function opens a patch in the directory dir
int pd_openpatch(char* patch, char* dir) {
#ifdef HAVE_PD
	//while (!sys_started) usleep(50);
	sys_lock();
	glob_evalfile(NULL, gensym(patch), gensym(dir));
	sys_unlock();
#endif /* HAVE_PD */
	return 0;
}

/**
 * Send a message to Pd
 */
void pd_send(char* recv, char* mess, char* fmt, ...) {
#ifdef HAVE_PD
	va_list ap;
	t_atom arg[10], *at =arg;
	int nargs = 0;
	char *fp = fmt;
	t_pd* x = gensym(recv)->s_thing;
	t_symbol* sel = gensym(mess);
	if (!x) return;

	va_start(ap, fmt);
	while (1)
	{
		if (nargs > 10)
		{
			pd_error(x, "pd_send: only %d allowed", MAXPDARG);
			break;
		}
		switch(*fp++)
		{
			case 'f': SETFLOAT(at, va_arg(ap, double)); break;
			case 's': SETSYMBOL(at, va_arg(ap, t_symbol *)); break;
			case 'i': SETFLOAT(at, va_arg(ap, t_int)); break;
			case 'p': SETPOINTER(at, va_arg(ap, t_gpointer *)); break;
			default: goto done;
		}
		at++;
		nargs++;
	}
	done:
	va_end(ap);
	sys_lock();
	typedmess(x, sel, nargs, arg);
	sys_unlock();
#endif /* HAVE_PD */
}

// dummy function if no pd is there
#ifndef HAVE_PD
t_symbol *gensym(const char *s) {
	return NULL;
}
#endif /* NOT HAVE_PD */
